<template>
  <div>
    <div style="font-size:18px;">角色管理</div>
    <hr>
    <br>
          <!-- <div style="float: right">
              <el-button @click="editRole()" type="danger">添加角色</el-button>
          </div> -->
          <el-table :data="roleData" border style="width: 100%"  >
              <el-table-column prop="name" label="角色名称" ></el-table-column>
              <el-table-column prop="domain" label="所在域名" ></el-table-column>
               <el-table-column label="操作" >
                  <template scope="scope">
                      <el-button size="small" @click="editRole(scope.row)">修改信息</el-button>
                      <el-button size="small" @click="editRolePrivilege(scope.row)">修改权限</el-button>
                  </template>
               </el-table-column>
          </el-table>
          <el-dialog title="修改角色权限" :visible.sync="dialogFormVisible" >
               <div style="text-align:center;">
                  <div style="text-align:left;width:480px;margin:0 auto;">
                      <div style="line-height:30px;">权限 <span style="color:red;">{{rolePriName}}</span> 修改</div>
                       <!-- <el-transfer
                          v-model="rolePriValue"
                          :props="{key: 'id',label:'name'}"
                          :data="rolePriData" 
                          :titles="rolePriTitle">
                        </el-transfer> -->
                        <el-tree :data="rpTreeValue" ref="rpTree"
                          show-checkbox
                          node-key="id"
                          :default-expanded-keys="[]"
                          :default-checked-keys="[]"
                          :props="defaultProps">
                        </el-tree>
                      </div>
                </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveRolePrivilege()">保 存</el-button>
            </div>
          </el-dialog>
          <el-dialog :title="titleName" :visible.sync="editDialog" >
               <div style="text-align:center;">
                  <div style="text-align:left;width:480px;margin:0 auto;">
                    <el-form :model="ruleForm4" :rules="rules4" ref="ruleForm4" label-width="100px" class="demo-ruleForm" style="width:60%;" >
                        <el-form-item prop="id"  style="display:none;" label="用户名称">
                             <el-input v-model="ruleForm4.id" placeholder=""  ></el-input>
                        </el-form-item>
                        <el-form-item prop="name" label="角色名称">
                           <el-input v-model="ruleForm4.name" placeholder="角色名称"  ></el-input>
                        </el-form-item>
                        <el-form-item prop="domain" label="对应域名">
                           <el-input v-model="ruleForm4.domain" placeholder="对应域名"  ></el-input>
                        </el-form-item>
                    </el-form>
                  </div>
                </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="editDialog = false">取 消</el-button>
              <el-button type="primary" @click="saveOrUpdateRole()">保 存</el-button>
            </div>
          </el-dialog>
  </div>
</template>
<script>
    import $ from 'jquery';
    import Vue from 'vue';

  export default {
    data() {
        return {
            activeName: 'first',
            userData: [],
            roleData:[],
            priData:[],

            cur_page: 1,
            page_size:10,
            total:0,
            multipleSelection: [],

            ruleForm: {
                username: '',
                acount: '',
                roleId:''
            },
            roleOptions:[],
            ruleForm2:{
                pname:'',
                paddress:''
            },
            ruleForm3:{
                id:'',
                name:'',
                imenu:'0',
                address:'',
                pid:'',
                remark:''
            },
            ruleForm4:{
                id:'',
                name:'',
                domain:'',
            },
            rules: {
                username: [],
            },
            rules3: {
                name: [
                    {required: true, message: '请输入权限名', trigger: 'blur'}
                ],

                // address: [
                //     { trigger: 'blur',validator: this.validatePriUrl}
                // ],
                
            },
            rules4: {
                name: [
                    {required: true, message: '请输入权限名', trigger: 'blur'},
                ],
                domain: [
                    {required: true, message: '请输入域名', trigger: 'blur'},
                ],
            },
            searchUrl:"/user/list",
            searchData:{},
            table:'userData',

            dialogFormVisible:false,
            editDialog:false,

            rolePriData:{},
            rolePriValue:{},
            rolePriName:'',
            rolePriTitle:['未选择','已选择'],
            rolePriId:'',

            priMultipleSelection:[],
            priDialogFormVisible:false,

            priName:'添加权限',
            priCleanShow:false,
            priTree:[],
            priBTree:[],
            priPName:'',//选中父id的名字
            defaultProps: {
              children: 'children',
              label: 'name'
            },
            priUrl:true,
            rpTreeValue:{},
            titleName:'添加权限'
        };
    },
    created(){
        var self=this;

        self.searchUrl="/role/list";
        self.userData=[];
        self.table='roleData';
        
        self.getData();
        self.myajax("/role/list",{pageSize:1000},function(data){
            self.roleOptions=data.data.list;
        });
    },
    methods: {
        searchUser(){
            this.cur_page=1;
            this.getData();
        },
        handleClick(tab, event) {
            var self=this;
            //标签点击事件
            //console.log(tab, event);
            var tabname=tab.name;
            self.cur_page=1;
            self.total=0;
            if(tabname=='first'){
                self.searchUrl="/user/list";
                self.userData=[];
                self.table='userData';
            }else if(tabname=='second'){
                self.searchUrl="/role/list";
                self.userData=[];
                self.table='roleData';
            }else if(tabname=='third'){
                self.searchUrl="/privilege/list";
                self.priData=[];
                self.table='priData';
            }else{

            }
            self.getData();
        },
        handleCurrentChange(val){//翻页
            this.cur_page = val;
            this.getData();
        },
        handleSizeChange(val) {//每页数量
            this.page_size=val;
            this.getData();
        },
        getData(){
            let self = this;
            var data=self.searchData;
            data.pageSize=self.page_size
            data.pageNumber=self.cur_page;
            data.param=new Object();
            data.param.username=self.ruleForm.username;
            data.param.realName=self.ruleForm.acount;
            data.param.roleId=self.ruleForm.roleId;
            data.param.pname=self.ruleForm2.pname;
            data.param.paddress=self.ruleForm2.paddress;
             self.myajax(self.searchUrl,data,function(data){
                    //console.log(data)
                   self[self.table]=data.data.list;
                   self['total']=data.data.total;
            });
           /* this.$axios.post(self.$host+"/user/list",{page:self.cur_page,token:token}).then((res) => {
                console.log(res.data);
                //self.userData = res.data.data;
            })*/
        },
        formatter(row, column) {
            return row.address;
        },
        formatterCreateDate(row,column){
            var date = row.createDate;  
              if (date == undefined) {  
                 return "";  
              } 
              return new Date(date).format("yyyy-MM-dd h:m");
        },
        formatterBirthday(row,column){
            var date = row.birthday;  
              if (date == undefined) {  
                 return "";  
              } 
              return new Date(date).format("yyyy-MM-dd");
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        handleEdit(index, row) {
            this.$message('编辑第'+(index+1)+'行');
        },
        handleDelete(index, row) {
            this.$message.error('删除第'+(index+1)+'行');
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        freezeUser(type,id){//冻结解冻用户
            var self=this;
            if(type!=0&&type!=1){
                self.$notify({title: '提示',message: '传入类型不正确',type: 'warning'});
                return;
            }
            var ids=new Array();
             if(id){
                ids.push(id);
            }else{
                if(self.multipleSelection.length==0){
                    self.$notify({title: '提示',message: '请先选择用户',type: 'warning'});
                    return;
                }
                for(var k in this.multipleSelection){
                    ids.push(this.multipleSelection[k].id);
                }
            }
            self.$confirm('确定要'+(type==0?"启用用户":"冻结用户")+', 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var data={type:type,uids:ids};
              self.myajax("/user/freeze",data,function(data){
                    var code=data.code;
                    if(code==2000){
                        self.$notify({title: '提示',message: (type==0?"启用用户":"冻结用户")+"成功",type: 'success'});
                    }else if(code==2001){
                        self.$notify({title: '提示',message:"传入类型不正确",type: 'error'});
                    }else if(code==2002){
                        self.$notify({title: '提示',message:"没有用户信息",type: 'error'});
                    }
                    self.getData();

              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });          
            });
        },
        // stopCommon(type,id){//禁言.解除禁言
        //      var self=this;
        //     if(type!=0&&type!=1){
        //         self.$notify({title: '提示',message: '传入类型不正确',type: 'warning'});
        //         return;
        //     }
        //     var ids=new Array();
        //      if(id){
        //         ids.push(id);
        //     }else{
        //         if(self.multipleSelection.length==0){
        //             self.$notify({title: '提示',message: '请先选择用户',type: 'warning'});
        //             return;
        //         }
        //         for(var k in this.multipleSelection){
        //             ids.push(this.multipleSelection[k].id);
        //         }
        //     }
        //     self.$confirm('确定要'+(type==1?"用户禁言":"解除禁言")+', 是否继续?', '提示', {
        //       confirmButtonText: '确定',
        //       cancelButtonText: '取消',
        //       type: 'warning'
        //     }).then(() => {
        //       var data={type:type,uids:ids};
        //       self.myajax("/user/comment",data,function(data){
        //             var code=data.code;
        //             if(code==2000){
        //                 self.$notify({title: '提示',message: (type==1?"用户禁言":"解除禁言")+"成功",type: 'success'});
        //             }else if(code==2001){
        //                 self.$notify({title: '提示',message:"传入类型不正确",type: 'error'});
        //             }else if(code==2002){
        //                 self.$notify({title: '提示',message:"没有用户信息",type: 'error'});
        //             }
        //             self.getData();

        //       });
        //     }).catch(() => {
        //       this.$message({
        //         type: 'info',
        //         message: '已取消操作'
        //       });          
        //     });
        // },
        editRole(row){//添加修改角色
            var self=this;
            if(row){
              self.titleName="修改角色";
              self.ruleForm4.id = row.id;
              self.ruleForm4.name = row.name;
              self.ruleForm4.domain = row.domain;
            }else{
              self.titleName="添加角色";
              self.ruleForm4.id = '';
              self.ruleForm4.name = '';
              self.ruleForm4.domain = '';
            }
            self.editDialog = true;
        },
        saveOrUpdateRole(){
          var self = this;
          self.$refs['ruleForm4'].validate((valid) => {
              if (valid) {
                    self.$confirm('确定要' + self.titleName + '?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                          var url="/role/create";
                          var data={
                            id:self.ruleForm4.id,
                            name:self.ruleForm4.name,
                            domain:self.ruleForm4.domain,
                          };
                          if(data.id){
                              url="/role/update"
                          }
                          self.myajax(url,data,function(data){
                              var code=data.code;
                              if(code==1000){
                                  self.$notify({title: '提示',message:"操作成功",type: 'success'});
                                  self.getData();
                                  self.editDialog = false;
                              }else{
                                  self.$notify({title: '提示',message: data.message,type: 'waring'});
                              }
                        });
                      }).catch(() => {
                          self.$message({
                            type: 'info',
                            message: '已取消操作'
                          });          
                  });
              }
          });
            
        },
/*        editRolePrivilege(row){
            var self=this;

            self.rolePriId=row.id;
            self.rolePriName=row.name;
            var rid=row.id;
            var data={rid:rid};
            self.myajax("/privilege/list",{pageSize:1000},function(pdata){//取得所有
                self.dialogFormVisible=true;
                self.rolePriData=pdata.data;
                self.myajax("/privilege/getPrivilegeByRoleId",data,function(data){
                    var bdata=data.data;
                    var values=new Array();
                   if(bdata){
                        for(var k in bdata){
                            values.push(bdata[k].id);
                        }
                   }
                   self.rolePriValue=values;
                });
            });
        },*/
        editRolePrivilege(row){
          
          var self=this;

          self.rolePriId=row.id;
          self.rolePriName=row.name;
          var rid=row.id;
          var data={rid:rid};
          self.myajax("/privilege/list",{pageSize:1000},function(pdata){//取得所有
              self.dialogFormVisible=true;
              self.rpTreeValue=self.beTree(pdata.data.list);
              self.myajax("/privilege/getPrivilegeByRoleId",data,function(data){
                  var bdata=data.data;
                  var values=new Array();
                 if(bdata){
                      for(var k in bdata){
                          values.push(bdata[k].id);
                      }
                 }
                 //console.log(self.$refs.rpTree);
                 Vue.nextTick(function(){
                    self.$refs.rpTree.setCheckedKeys(values);
                 })
                 
              });
          });
        },
        saveRolePrivilege(rid){//保存角色的权限
            var self=this;
            var rid=self.rolePriId;
            //var pids=self.rolePriValue;
            var pids=self.$refs.rpTree.getCheckedKeys();
            var data={rid:rid,pids:pids};
            self.myajax("/role_privilege/updatePrivilegeByRoleId",data,function(data){
                self.$notify({title: '提示',message:"修改成功",type: 'success'});
                self.dialogFormVisible = false;
            });
        },
        editPrivilege(row){
            var self=this;


            self.priName="修改权限信息"
            this.ruleForm3.id=row.id;
            this.ruleForm3.name=row.name;
            this.ruleForm3.address=row.address;
            this.ruleForm3.remark=row.remark;
            this.ruleForm3.imenu=row.imenu+"";
            if(!row.imenu)
              this.ruleForm3.imenu="0";
            this.ruleForm3.pid=row.pid;
            var btree=self.priBTree;
            if(btree&&row.pid){
              for(var k in btree){
                if(btree[k].id==row.pid){
                  self.priPName=btree[k].name;
                  self.priCleanShow=true;
                  self.priBTree.splice(k,1);
                  self.deleteTreeById(self.priTree,row.id);
                }
              }
            }
            self.changePri();
            self.priDialogFormVisible = true;
        },
        updatePrivilege(){
            var self=this;
            this.$refs['ruleForm3'].validate((valid) => {
              if(valid){
                var data={};
                var id=self.ruleForm3.id;
                data.name=self.ruleForm3.name;
                data.address=self.ruleForm3.address;
                data.remark=self.ruleForm3.remark;
                data.imenu=self.ruleForm3.imenu+"";
                data.pid=self.ruleForm3.pid;
                var url="/privilege/add";
                if(id){
                    url="/privilege/update";
                    data.id=id;
                }

                self.myajax(url,data,function(data){
                    self.$notify({title: '提示',message:"修改成功",type: 'success'});
                    self.priDialogFormVisible = false;
                });
                this.getData();
              }
            });
        },
        deletePrivilege(id){//禁言.解除禁言
            var self=this;
            var ids=new Array();
             if(id){
                ids.push(id);
            }else{
                if(self.priMultipleSelection.length==0){
                    self.$notify({title: '提示',message: '请先选择权限',type: 'warning'});
                    return;
                }
                for(var k in this.priMultipleSelection){
                    ids.push(this.priMultipleSelection[k].id);
                }
            }
            self.$confirm('确定要删除权限?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var data={ids:ids,test:'1'};
              self.myajax("/privilege/delete",data,function(data){
                    var code=data.code;
                    if(code==2000){
                        self.$notify({title: '提示',message: "删除成功",type: 'success'});
                    }else if(code==2004){
                        self.$notify({title: '提示',message:"没有订单信息",type: 'error'});
                    }
                    self.getData();

              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });          
            });
        },
        priHandleSelectionChange(val) {
            this.priMultipleSelection = val;
        },
        resetForm3(formName) {
          var self=this;
          var data=self.searchData;
          data.pageSize=1000;
          data.pageNumber=1;
          data.param=new Object();
          data.param.imenu="1";
          self.myajax(self.searchUrl,data,function(data){
                  //console.log(data)
                  if(data.data.list){
                   self.priTree=data.data.list;
                   self.priBTree=new Array().concat(data.data.list);
                   self.beTree(self.priTree);
                 }else{
                   self.priTree=[];
                   self.priBTree=[];
                 }
          },true);

          this.priName="添加权限信息"
          this.ruleForm3.id='';
          this.ruleForm3.name='';
          this.ruleForm3.address='';
          this.ruleForm3.remark='';
          this.ruleForm3.imenu="0";
          this.ruleForm3.pid="";
          this.priPName="";
          self.priCleanShow=false;
          self.changePri();
        },
        checkChange(p1,p2,p3){
          var self=this;
          var pid=p1.pid;
          this.ruleForm3.pid=p1.id;
          this.priPName=p1.name;
          self.priCleanShow=true;
        },
        beTree(data){
          for(var k in data){
            var bdata=data[k];
            var id=bdata.id;
            genTree(id,bdata,data);
          }
          function genTree(pid,bdata,data){
            for(var k in data){
              var gdata=data[k];
              if(gdata.pid&&gdata.pid==pid&&pid!=gdata.id){
                gdata.self_issub=true;
                if(bdata.children){
                  bdata.children.push(gdata);
                }else{
                  bdata.children=new Array();
                  bdata.children.push(gdata);
                }
              }
            }
          }
          for(var i=data.length-1;i>=0;i--){
            var bdata=data[i];
            if(bdata.self_issub){
              data.splice(i,1);
            }
          }
          return data;
        },
        deleteTreeById(tree,id){
          for(var k in tree){
            var btree=tree[k];
            if(btree.id==id){
              tree.splice(i,1);
            }
          }
        },
        changePri(){
          var self=this;
          var par=self.ruleForm3.imenu;
          if(par=='1'){
            self.priUrl=false;
          }else{
            self.priUrl=true;
          }
        },
        cleanPri(){
          var self=this;
          self.ruleForm3.pid='';
          self.priPName='';
          self.priCleanShow=false;
        },
        validatePriUrl(rule, value, callback){
          var self=this;
          var par=self.ruleForm3.imenu;
          if(par=='1'){
            self.ruleForm3.address=''
            callback();
          }else{
            if(self.ruleForm3.address=='')
            callback(new Error('请输入权限链接'));
             callback();
          }
        }
    }
  };
</script>
<style scoped>
    .input_edit{
        width: 200px;
        float: left;
        margin-right:10px;
    }
    .cell{
        padding: 0 5px !important;
        overflow: auto;
    }
</style>
